﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PatternCommand
{
    /// <summary>
    /// 命令模式   常用于前后端的链接
    /// </summary>
    class Program
    {
        static void Main(string[] args)
        {
            //GUI控件定义
            SaveButton save = new SaveButton(); 
            TextBox box = new TextBox();
             
            //后端命令定义
            ICommand command = new PrintCommand(box);
            save.BindCommand(command);//将命令和前端控件绑定
           
            //对前端控件赋值
            box.SetContext("aaaaaa");
            //由前端控件触发后端命令 
            save.DoExecute();



            command = new AddPerixCommand(box);
            save.BindCommand(command);
            //对前端控件赋值
            box.SetContext("aaaaaa");
            //由前端控件触发后端命令 
            save.DoExecute();

            Console.ReadKey();
        }
    }


    interface ICommand
    {
        void Execute();
    }

    class SaveButton
    {
        private ICommand command;

        public void BindCommand(ICommand _command)
        {
            this.command = _command;
        }
        public void DoExecute()
        {
            if (command == null)
                throw new Exception("!!");
            command.Execute();
        }
    }

    class AddPerixCommand : ICommand
    {
        PrintService printService = new PrintService();
        TextBox textBox;

        public AddPerixCommand(TextBox _box)
        {
            this.textBox = _box;
        } 
        public void Execute()
        {
            printService.Print( "perix-" + textBox.GetContext());
        }
    }

    class PrintCommand : ICommand
    {
        PrintService printService = new PrintService();
        TextBox textBox;

        public PrintCommand(TextBox _box)
        {
            this.textBox = _box;
        }

        public void Execute()
        {
            printService.Print(textBox.GetContext());
        }
    }


    class TextBox
    {
        string text;
        public  string GetContext( )
        {
            return text; 
        }
        public void SetContext(string _text)
        { 
            this.text = _text;
        }
    }

    class PrintService {

        public void Print(string text)
        {
            Console.WriteLine(text);
        }
    }




}
